import React, { useState, useEffect } from 'react';
import { Table, Typography, Space, Tag, Button, Empty, message, Popconfirm } from 'antd';
import { FilePdfOutlined, FileTextOutlined, DeleteOutlined, ReloadOutlined } from '@ant-design/icons';
import { exportService } from '../../../services/export/exportService';
import { ExportHistoryItem } from '../../../services/export/types';

const { Text } = Typography;

export const ExportHistory: React.FC = () => {
  const [historyData, setHistoryData] = useState<ExportHistoryItem[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    loadHistory();
  }, []);

  const loadHistory = async () => {
    setLoading(true);
    try {
      const history = await exportService.getExportHistory();
      setHistoryData(history);
    } catch (error) {
      console.error('[ExportHistory] 加载导出历史失败:', error);
      message.error('加载导出历史失败');
    } finally {
      setLoading(false);
    }
  };

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const formatDateTime = (timestamp: number): string => {
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const clearHistory = async () => {
    try {
      // 这里需要在exportService中添加清空历史的方法
      // 暂时通过直接操作LocalStorage来实现
      if (typeof window !== 'undefined' && window.localStorage) {
        window.localStorage.removeItem('rmzf:export:history');
        setHistoryData([]);
        message.success('导出历史已清空');
      } else {
        throw new Error('LocalStorage不可用');
      }
    } catch (error) {
      console.error('[ExportHistory] 清空历史失败:', error);
      message.error('清空历史失败');
    }
  };

  const columns = [
    {
      title: '文件名',
      dataIndex: 'filename',
      key: 'filename',
      width: '35%',
      render: (filename: string, record: ExportHistoryItem) => (
        <Space>
          {record.format === 'pdf' ? (
            <FilePdfOutlined style={{ color: '#ff4d4f' }} />
          ) : (
            <FileTextOutlined style={{ color: '#1890ff' }} />
          )}
          <Text copyable={{ text: filename }}>{filename}</Text>
        </Space>
      )
    },
    {
      title: '格式',
      dataIndex: 'format',
      key: 'format',
      width: '10%',
      render: (format: string) => (
        <Tag color={format === 'pdf' ? 'red' : 'blue'}>
          {format.toUpperCase()}
        </Tag>
      )
    },
    {
      title: '文件大小',
      dataIndex: 'size',
      key: 'size',
      width: '15%',
      render: (size: number) => (
        <Text type="secondary">{formatFileSize(size)}</Text>
      )
    },
    {
      title: '导出时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: '25%',
      render: (timestamp: number) => (
        <Text type="secondary">{formatDateTime(timestamp)}</Text>
      )
    },
    {
      title: '导出设置',
      key: 'options',
      width: '15%',
      render: (_: any, record: ExportHistoryItem) => {
        const options = record.options;
        const optionText = record.format === 'pdf' 
          ? `${(options as any).format || 'A4'} ${(options as any).orientation || 'portrait'}`
          : `${(options as any).template || 'standard'} ${(options as any).fontSize || 12}pt`;
        
        return <Text type="secondary">{optionText}</Text>;
      }
    }
  ];

  if (historyData.length === 0 && !loading) {
    return (
      <div style={{ textAlign: 'center', padding: '40px 0' }}>
        <Empty
          description="暂无导出历史"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        >
          <Text type="secondary">
            您还没有导出过任何文档，导出后的记录将显示在这里
          </Text>
        </Empty>
      </div>
    );
  }

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Text type="secondary">
          共 {historyData.length} 条导出记录
        </Text>
        <Space>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={loadHistory}
            loading={loading}
            size="small"
          >
            刷新
          </Button>
          {historyData.length > 0 && (
            <Popconfirm
              title="确认清空所有导出历史记录？"
              description="此操作不可恢复"
              onConfirm={clearHistory}
              okText="确认"
              cancelText="取消"
            >
              <Button 
                icon={<DeleteOutlined />} 
                danger
                size="small"
              >
                清空历史
              </Button>
            </Popconfirm>
          )}
        </Space>
      </div>
      
      <Table
        columns={columns}
        dataSource={historyData}
        rowKey="id"
        loading={loading}
        size="small"
        pagination={{
          pageSize: 10,
          showSizeChanger: false,
          showQuickJumper: true,
          showTotal: (total, range) => 
            `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
        }}
        scroll={{ y: 300 }}
      />
    </div>
  );
};